import iconUser from '@/assets/img/icon-user.png';
import { Icon, useCall, useResourceTree } from '@/components';
import useLoginUser from '@/components/auth/useLoginUser';
import styles from '@/components/Layout/index.less';
import AppLayout from '@/components/Layout/layout';
import resourceData from '@/constants/productResources.json';
import { UserActions } from '@/reducers/user';
import { on } from '@/utils';
import { Avatar, Dropdown, Menu, Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import RouteConfig from './RouteConfig';

function App(props) {
  const history = useHistory();
  const dispatch = useDispatch();
  const [resource, setResources] = useState(resourceData);
  const menuData = useResourceTree(resource);

  useEffect(
    () =>
      on(window, 'message', (e) => {
        let menuData = e.data.menu;
        if (!Array.isArray(menuData)) return;

        console.log(menuData);
        function each(item) {
          const parentId = this?.code || '0';
          const { code: id, name: resourceName, icon, url, child = [] } = item;
          return [{ id, parentId, resourceName, resourceType: 'M', icon, url }, ...child.flatMap(each, item)];
        }
        menuData = menuData.flatMap(each, {});
        console.log({ menuData });

        setResources(menuData);
      }),
    [],
  );

  const loginUser = useLoginUser();
  const handleMenu = useCall((menuItem) => {
    switch (menuItem.key) {
      case 'changePwd':
        history.push('/changePwd');
        break;
      case 'logout':
        Modal.confirm({
          title: '提示信息',
          content: '确认退出吗?',
          type: 'warning',
          onOk() {
            dispatch(UserActions.logout());
          },
        });
        break;
    }
  });

  const menu = (
    <Menu onClick={handleMenu}>
      <Menu.Item key='changePwd'>修改密码</Menu.Item>
      <Menu.Item key='logout'>退出登录</Menu.Item>
    </Menu>
  );

  const dropdownMenu = (
    <Dropdown overlay={menu}>
      <div className={styles.dropdown}>
        <Avatar gap={8} src={iconUser} />
        <span>{loginUser?.userAccount ?? 'Admin'}&nbsp;</span>
        <Icon type='down' />
      </div>
    </Dropdown>
  );

  return (
    <AppLayout {...props} hideHead hideNav menuTree={menuData} dropdownMenu={dropdownMenu} parentPath='/product'>
      {menuData?.length > 0 && <RouteConfig menuTree={menuData} parentPath='/product' />}
    </AppLayout>
  );
}

export default App;
